//
//  LRXHelpItemModel.m
//  路人侠
//
//  Created by zhangxulong on 5/29/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXHelpItemData.h"

@interface LRXHelpItemData(){
    std::list<LRXHistroyHelpItemModel *>items;
}/**
 *  page 当前的页数
 */
@property (nonatomic,assign) NSInteger  page;

@property (nonatomic,assign) NSInteger firstFlag;

@property (nonatomic,copy) HistroyLoadDataBlock  histroyMoreDataBlock;
@property (nonatomic,copy) HistroyLoadFaildBlock  histroyMoreDataFailBlock;
@end

@implementation LRXHelpItemData



- (instancetype)initWithItemsWithMoreDataBlock:(HistroyLoadDataBlock) MoreDataBlock
                            moreDataFaildBlock:(HistroyLoadFaildBlock) moreDataFaildBlock;
{
    if (self = [super init]) {
        self.histroyMoreDataBlock = [MoreDataBlock copy];
        self.histroyMoreDataFailBlock = [moreDataFaildBlock copy];
        
        self.page = 0;
        self.firstFlag = 0;
    }
    return self;
}

//加载更多的数据
- (void)loadMoreInfo:(NSString *)url
{
    __weak id weakSelf = self;
    [MBProgressHUD showMessage:nil];
    //有下一页
    if (self.page > 0 || !self.firstFlag)
    {
        NSDictionary * parm = @{@"page":[NSString stringWithFormat:@"%ld",self.page + 1] };
        AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
        [manger GET:url parameters:parm progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [MBProgressHUD hideHUD];
            LRXHelpItemData * strongSelf = weakSelf;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * nextPage = responseObject[@"data"][@"next_page"];
                
                strongSelf.page = [nextPage integerValue];
                
                for (NSDictionary * dic in responseObject[@"data"][@"dataset"]) {
                    LRXHistroyHelpItemModel * helpMesgs = [LRXHistroyHelpItemModel histroyHelpWithDic:dic];
                    items.push_back(helpMesgs); //尾部添加新的数据
                }
                strongSelf.histroyMoreDataBlock(items);
            });
            
            
            strongSelf.firstFlag = 1;
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUD];
            LRXHelpItemData * strongSelf = weakSelf;
            strongSelf.histroyMoreDataFailBlock();
        }];
    }
}
@end
